package com.easy.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsV2Request;
import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import com.easy.mapper.EmployeeDao;
import com.easy.service.OssCleanupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class OssCleanupServiceImpl implements OssCleanupService {
    
    private static final Logger logger = LoggerFactory.getLogger(OssCleanupServiceImpl.class);
    
    // OSS配置信息
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static final String BUCKET_NAME = "erpandmes";
    private static final String ACCESS_KEY_ID = "LTAI5tSixwkn4sLbzXLKJihn";
    private static final String ACCESS_KEY_SECRET = "HVx1c7dRrpLK1cjUa1imekGHNqjyYp";
    
    @Autowired
    private EmployeeDao employeeDao;
    
    /**
     * 定时清理OSS中未使用的图片
     * 每天凌晨2点执行一次
     */
    @Override
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupUnusedImages() {
        logger.info("开始执行OSS未使用图片清理任务");
        
        try {
            // 1. 获取数据库中所有在用的图片URL
            Set<String> usedImages = getUsedImagesFromDatabase();
            logger.info("数据库中共有 {} 个在用图片", usedImages.size());
            
            // 2. 获取OSS中所有图片
            Set<String> ossImages = getAllImagesFromOSS();
            logger.info("OSS中共有 {} 个图片", ossImages.size());
            
            // 3. 计算未使用的图片
            Set<String> unusedImages = new HashSet<>(ossImages);
            unusedImages.removeAll(usedImages);
            logger.info("发现 {} 个未使用的图片", unusedImages.size());
            
            // 4. 删除未使用的图片
            if (!unusedImages.isEmpty()) {
                deleteImagesFromOSS(unusedImages);
                logger.info("成功删除 {} 个未使用的图片", unusedImages.size());
            } else {
                logger.info("没有发现未使用的图片");
            }
            
        } catch (Exception e) {
            logger.error("清理OSS未使用图片时发生错误", e);
        }
        
        logger.info("OSS未使用图片清理任务执行完毕");
    }
    
    /**
     * 从数据库中获取所有在用的图片URL
     * @return 在用图片URL集合
     */
    private Set<String> getUsedImagesFromDatabase() {
        Set<String> usedImages = new HashSet<>();
        
        // 获取所有未删除的员工记录
        List<com.easy.bean.Employee> employees = employeeDao.all(null, null);
        
        // 收集所有在用的图片URL
        for (com.easy.bean.Employee employee : employees) {
            if (employee.getPhoto() != null && !employee.getPhoto().isEmpty()) {
                // 从完整URL中提取文件名
                String photoUrl = employee.getPhoto();
                String fileName = extractFileNameFromUrl(photoUrl);
                if (fileName != null && !fileName.isEmpty()) {
                    usedImages.add(fileName);
                }
            }
        }
        
        return usedImages;
    }
    
    /**
     * 从URL中提取文件名
     * @param url 完整的图片URL
     * @return 文件名
     */
    private String extractFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        
        // 例如：https://erpandmes.oss-cn-beijing.aliyuncs.com/abc.jpg
        int lastSlashIndex = url.lastIndexOf('/');
        if (lastSlashIndex >= 0 && lastSlashIndex < url.length() - 1) {
            return url.substring(lastSlashIndex + 1);
        }
        
        return url;
    }
    
    /**
     * 获取OSS中所有图片
     * @return OSS中所有图片文件名集合
     */
    private Set<String> getAllImagesFromOSS() {
        Set<String> ossImages = new HashSet<>();
        
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        
        try {
            // 列出存储桶中的所有对象
            ListObjectsV2Request request = new ListObjectsV2Request(BUCKET_NAME);
            request.setMaxKeys(1000); // 每次最多获取1000个对象
            
            ListObjectsV2Result result;
            do {
                result = ossClient.listObjectsV2(request);
                
                // 收集所有对象的文件名
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    ossImages.add(objectSummary.getKey());
                }
                
                // 如果还有更多对象，继续获取下一批
                request.setContinuationToken(result.getNextContinuationToken());
            } while (result.isTruncated());
            
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        
        return ossImages;
    }
    
    /**
     * 从OSS中删除指定的图片
     * @param imagesToDelete 要删除的图片文件名集合
     */
    private void deleteImagesFromOSS(Set<String> imagesToDelete) {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        
        try {
            // 批量删除
            for (String imageName : imagesToDelete) {
                ossClient.deleteObject(BUCKET_NAME, imageName);
                logger.debug("已删除OSS中的图片: {}", imageName);
            }
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}